#include "Olympus.h"
#include "SubObject.h"


namespace Win32 {


	SubObject::SubObject(std::wstring className, std::wstring classTitle, HICON icon)
		: m_Class(className), m_Title(classTitle), m_hIcon(icon)
	{
	}

	SubObject::~SubObject()
	{
	}

	VOID SubObject::RegisterNewClass() {
        WNDCLASSEX wcex;

        wcex.cbSize = sizeof(WNDCLASSEX);

        wcex.style = CS_HREDRAW | CS_VREDRAW;
        wcex.lpfnWndProc = SetupMessapeHandler;
        wcex.cbClsExtra = 0;
        wcex.cbWndExtra = 0;
        wcex.hInstance = HInstance();
        wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
        wcex.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(50, 50, 50));
        wcex.lpszMenuName = nullptr;
        wcex.lpszClassName = m_Class.c_str();

        wcex.hIcon = m_hIcon;
        wcex.hIconSm = m_hIcon;

        RegisterClassEx(&wcex);
    }

    LRESULT SubObject::SetupMessapeHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
        if (message == WM_NCCREATE) {
            const CREATESTRUCTW* const pCreate = reinterpret_cast<CREATESTRUCTW*>(lParam);
            Win32::SubObject* const pWnd = static_cast<Win32::SubObject*>(pCreate->lpCreateParams);
            SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pWnd));
            SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&Win32::SubObject::AssignMessageHandler));
            return pWnd->MessageHandler(hWnd, message, wParam, lParam);
        }
        return DefWindowProc(hWnd, message, wParam, lParam);
    }

    LRESULT SubObject::AssignMessageHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
        SubObject* const pWnd = reinterpret_cast<SubObject*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
        return pWnd->MessageHandler(hWnd, message, wParam, lParam);
    }

    LRESULT SubObject::ConmonMessapeHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
        switch (message) {
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
        return 0;
    }

}
